package com.wsd.smartcarwasher.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.domain.Machine;
import com.wsd.smartcarwasher.domain.OrderInfo;
import com.wsd.smartcarwasher.util.HttpClientUtil;
import com.wsd.smartcarwasher.util.HttpResult;
import com.wsd.smartcarwasher.util.PostImgUpload;
import com.wsd.smartcarwasher.util.StringUtil;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import sun.net.www.content.image.png;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * 萤石设备摄像头获取
 */

@Service
public class LappService {

    @Resource
    private RedisService redisService;
    @Resource
    private OrderService orderService;

    private final  static  Logger logger=LoggerFactory.getLogger(LappService.class);

    /**
     * 获取accesstoken
     * @return
     */
        public  String getAccessToken()
        {
            if(!JSONUtil.isNull(this.redisService.get("AccessToken")))
            {
                String accessToken=this.redisService.get("AccessToken").toString();
                String[] expiredTime=accessToken.split(",");
                List<String> stringList = Arrays.asList(expiredTime);
                if(DateUtil.current()<Long.parseLong(stringList.get(1)))
                {
                    System.out.println("accesstoken未过期"+stringList.get(0));
                    return stringList.get(0);
                }
            }
            String response =null;
            String url = "https://open.ys7.com/api/lapp/token/get";
            Map<String, Object> parmarMap = new HashMap<>();
            parmarMap.put("appKey", Constant.YSAPPKey);
            parmarMap.put("appSecret", Constant.YSAPPSecret);
            try{
                response= HttpUtil.post(url,parmarMap);
                JSONObject jsonObject=JSONUtil.parseObj(response);
                if(jsonObject.getStr("code").equals("200"))
                {
                    String accessToken=jsonObject.getJSONObject("data").getStr("accessToken");
                    long expireTime=jsonObject.getJSONObject("data").getLong("expireTime");
                    this.redisService.put("AccessToken",accessToken+","+expireTime,7200L);
                    return accessToken;
                }
            }catch (Exception e)
            {
                logger.info("获取accessToken失败");
                e.printStackTrace();
            }
            return null;
        }


    /**
     *  抓拍洗车前照片和洗车后照片  目前改动是上传至七牛
      * @param deviceSerial
     * @param channelNo
     * @return
     */
    public  String getWashStartPhoto(String deviceSerial,Integer channelNo)
    {
        //萤火虫地址
        String response =null;
        String url = "https://open.ys7.com/api/lapp/device/capture";
        String picUrl=null;
    try{
        Map<String, Object> parmarMap=new HashMap();
        parmarMap.put("accessToken",this.getAccessToken());
        parmarMap.put("deviceSerial",deviceSerial);
        parmarMap.put("channelNo",channelNo);
        response= HttpUtil.post(url, parmarMap);
        JSONObject jsonObject=JSONUtil.parseObj(response);
        logger.debug("响应码响应结果:"+ jsonObject.toString());
        if(jsonObject.getStr("code").equals("200"))
        {
            System.out.println("以获取到图片");
            picUrl=jsonObject.getJSONObject("data").getStr("picUrl");
        }else{
            picUrl="https://luobotuchuang.ytby0402.top/washWaringImg.jpg";
        }
        return picUrl;

    }catch (Exception e)
    {
        System.out.println("获取accessToken失败");
        e.printStackTrace();
    }
        return "https://luobotuchuang.ytby0402.top/washWaringImg.jpg";
    }







    /**
     * 抓拍图片
     * @return
     */
    public  String getCapture(String deviceSerial,Integer channelNo)
    {
        //萤火虫地址
        String response =null;
        String url = "https://open.ys7.com/api/lapp/device/capture";
        String picUrl=null;
        try{
            Map<String, Object> parmarMap=new HashMap();
            parmarMap.put("accessToken",this.getAccessToken());
            parmarMap.put("deviceSerial",deviceSerial);
            parmarMap.put("channelNo",channelNo);
            response= HttpUtil.post(url, parmarMap);
            JSONObject jsonObject=JSONUtil.parseObj(response);
            logger.debug("响应码响应结果:"+ jsonObject.toString());
            if(jsonObject.getStr("code").equals("200"))
            {
                System.out.println("以获取到图片");
               picUrl=jsonObject.getJSONObject("data").getStr("picUrl");
            }else{
                picUrl="https://luobotuchuang.ytby0402.top/washWaringImg.jpg";
            }
            return picUrl;
        }catch (Exception e)
        {
            System.out.println("获取accessToken失败");
            e.printStackTrace();
        }
        return "https://luobotuchuang.ytby0402.top/washWaringImg.jpg";
    }

    /**
     *  rest api 发送消息
     * @param apiUrl  请求地址
     * @param map
     * @return
     */
    public static JSONObject httpConnect_send(String apiUrl, MultiValueMap<String, String> map) {
        JSONObject jsonObject = new JSONObject();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            List<MediaType> acceptableMediaTypes = new ArrayList<>();
            acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
            acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
            HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = new RestTemplate().postForEntity(apiUrl, requestParams, String.class);
            String result = response.getBody();
            jsonObject = JSONUtil.parseObj(result);
            jsonObject.put("responseCode","200");
        }catch (Exception e){
            jsonObject.put("responseCode","500");
        }
        return jsonObject;
    }

    /**
     * 保存订单洗车照片
     * @param orderInfo
     * @param machine
     */

    public  void  saveOrderCarWashImage(OrderInfo orderInfo, Machine machine)
    {
        //保存洗车前
       if(orderInfo.getConsumed()==0&&StringUtil.isNullOrEmpty(orderInfo.getBeforeCarPhoto()))
       {
           String s=this.getCapture(machine.getCameraCode(),2);
           orderInfo.setBeforeCarPhoto(uploadManwoByImgurl(s));
           this.orderService.saveOrderCarWashPhoto(orderInfo);
       }
       //保存洗车后
       if(orderInfo.getConsumed()==1&&StringUtil.isNullOrEmpty(orderInfo.getAfterCarPhoto()))
       {
           String s=this.getCapture(machine.getCameraCode(),2);
           orderInfo.setAfterCarPhoto(uploadManwoByImgurl(s));
           this.orderService.saveOrderCarWashPhoto(orderInfo);
       }
    }




    /**
     * 上传图片至漫涡文件服务器
     * @param imgUrl
     * @return
     */
    public static String  uploadManwoByImgurl(String imgUrl) {
        try {
            URL s=new URL(imgUrl);
            Img img1=Img.from(s);
            String filePath=Constant.IMAGE_PATH_PREFIX+System.currentTimeMillis()+".png";
            img1.write(FileUtil.file(filePath));
            try {
                return PostImgUpload.postImgUpload(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }






}
